package cn.dogeye.handlers;

import cn.dogeye.common.protocol.Result;
import cn.dogeye.util.RespUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class GlobalExceptionHanler implements HandlerExceptionResolver {
    //记录数据库最大字符长度
    private static final int WIRTE_DB_MAX_LENGTH = 1500;
    //记录数据库最大字符长度
    private static final short LOG_LEVEL = 6;
    //记录数据库最大字符长度
    private static final short LOG_OPT = 3;
    /**
     * 对异常信息进行统一处理，区分异步和同步请求，分别处理
     */
    @SneakyThrows
    public ModelAndView resolveException(HttpServletRequest request,
                                         HttpServletResponse response, Object handler, Exception ex) {
        boolean isajax = isAjax(request,response);
        Throwable deepestException = deepestException(ex);
        return processException(request, response, handler, deepestException, isajax);
    }

    /**
     * 判断当前请求是否为异步请求.
     */
    private boolean isAjax(HttpServletRequest request, HttpServletResponse response){
        return StringUtils.isNotEmpty(request.getHeader("X-Requested-With"));
    }
    /**
     * 获取最原始的异常出处，即最初抛出异常的地方
     */
    private Throwable deepestException(Throwable e){
        Throwable tmp = e;
        int breakPoint = 0;
        while(tmp.getCause()!=null){
            if(tmp.equals(tmp.getCause())){
                break;
            }
            tmp=tmp.getCause();
            breakPoint++;
            if(breakPoint>1000){
                break;
            }
        }
        return tmp;
    }
    /**
     * 处理异常.
     */
    private ModelAndView processException(HttpServletRequest request,
                                          HttpServletResponse response, Object handler,
                                          Throwable ex, boolean isajax) throws IOException {
        //步骤一、异常信息记录到日志文件中.
        log.error("全局处理异常捕获:", ex);
        //步骤二、异常信息记录截取前50字符写入数据库中.
        // logDb(ex);
        //步骤三、分普通请求和ajax请求分别处理.
        if(isajax){
            return processAjax(request,response,handler,ex);
        }else{
            return processNotAjax(request,response,handler,ex);
        }
    }
    /**
     * 异常写入数据库中
     */
    // private void logDb(Throwable ex) {
    //     //String exceptionMessage = getThrowableMessage(ex);
    //     String exceptionMessage = "错误异常: "+ex.getClass().getSimpleName()+",错误描述："+ex.getMessage();
    //     if(StringUtils.isNotEmpty(exceptionMessage)){
    //         if(exceptionMessage.length() > WIRTE_DB_MAX_LENGTH){
    //             exceptionMessage = exceptionMessage.substring(0,WIRTE_DB_MAX_LENGTH);
    //         }
    //     }
    // }
    /**
     * ajax异常处理并返回.
     */
    private ModelAndView processAjax(HttpServletRequest request,
                                     HttpServletResponse response, Object handler,
                                     Throwable deepestException) throws IOException {
        log.error("异步异常");
        ModelAndView empty = new ModelAndView();
        //response.setContentType("application/json");
        RespUtil.write(response, Result.fail(deepestException.getMessage()));
        empty.clear();
        return empty;
    }
    /**
     * 普通页面异常处理并返回.
     */
    private ModelAndView processNotAjax(HttpServletRequest request,
                                        HttpServletResponse response, Object handler, Throwable ex) {
        log.error("同步异常");
        String exceptionMessage = getThrowableMessage(ex);
        Map<String, Object> model = new HashMap<String, Object>();
        model.put("exceptionMessage", exceptionMessage);
        model.put("ex", ex);
        return new ModelAndView("common/error", model);
    }
    /**
     * 返回错误信息字符串
     */
    public String getThrowableMessage(Throwable ex) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        ex.printStackTrace(pw);
        return sw.toString();
    }
}
